<template>
  <div class="class-manage">
    <!-- <Breadcrumb /> -->
    <div class="header">
      <img
        class="back-icon"
        @click="router.go(-1)"
        src="@/assets/images/common/go-back.png"
      />
      <div class="tab-container">
        <div
          class="tab"
          :class="{ active: activeTab === 1 }"
          @click="activeTab = 1"
        >
          任课班级
        </div>
        <div
          class="tab"
          :class="{ active: activeTab === 2 }"
          @click="activeTab = 2"
        >
          管理班级
        </div>
      </div>
    </div>
    <div class="main">
      <div class="main-header">
        <div class="left">
          <span class="label">班级：</span>
          <el-cascader
            v-model="curClassId"
            :options="treeData"
            :teleported="false"
            :class="{ 'cascader-checked': cascadeVisible }"
            @visible-change="expandDropdown"
          />
          <el-input
            v-model="searchKey"
            class="w-50 m-2"
            placeholder="请输入学生姓名、学生学号、家长手机号"
            :prefix-icon="Search"
            @keyup.enter="onSearch"
          />
          <!-- <div class="search-button" @click="onSearch">搜索</div> -->
        </div>
        <div class="right">
          <span
            class="cancel-text"
            :class="{ 'split-line': selectedRow.length }"
            @click="switchVisibleRange"
            v-if="curClassType === CLASS_TYPE.TargetClass && activeTab === 2"
            >{{
              curVisible === VISIBLE_TYPE.OnlySelf
                ? `仅创建者${fromPerson}可见`
                : '同科目可见'
            }}</span
          >
          <span
            v-if="selectedRow.length"
            class="cancel-text"
            @click="multipleTableRef.clearSelection()"
            >取消选择</span
          >
          <div
            class="delete-button default"
            v-if="curClassType === CLASS_TYPE.TargetClass"
            @click="deletePopupVisible = true"
          >
            删除靶向班
          </div>
          <div
            class="create-button default"
            @click="onCreate"
            @mouseenter="handleShowDropdown(true)"
            @mouseleave="handleShowDropdown(false)"
          >
            <span> 创建靶向班（{{ selectedRow.length }}）</span>
            <!-- <div
              class="dropdown-container"
              v-if="selectedRow.length && dropdownVisible"
              @mouseenter="handleShowDropdown(true)"
              @mouseleave="handleShowDropdown(false)"
            >
              <ul class="student-list">
                <li
                  class="name-item"
                  v-for="(item, index) in selectedRow"
                  :key="index"
                >
                  {{ item.studentName }}
                </li>
              </ul>
              <img
                class="triangle"
                src="@/assets/images/workbench/triangle.svg?url"
              />
            </div> -->
          </div>
        </div>
      </div>

      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" label="状态" align="center" />
        <el-table-column prop="number" label="序号" align="center" />
        <el-table-column prop="className" label="班级" align="center" />
        <el-table-column prop="studentName" label="学生姓名" align="center" />
        <el-table-column prop="studentNum" label="学号" align="center" />
        <el-table-column
          label="操作"
          align="center"
          v-if="curClassType === CLASS_TYPE.TargetClass"
        >
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleShowDeleteStudent(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="8"
        @current-change="onPageChange"
      /> -->

      <!-- <div style="height: 100px; width: 100%;"></div> -->
    </div>

    <el-dialog v-model="deletePopupVisible" :show-close="false" border>
      <div class="tip-text">班级下可能有学生这样是否删除？</div>
      <div class="button-container">
        <div class="cancel default" @click="deletePopupVisible = false">
          取消
        </div>
        <div class="confirm default" @click="onDeleteTargeClass">确认</div>
      </div>
    </el-dialog>

    <el-dialog v-model="deleteStudentVisible" :show-close="false" border>
      <div class="tip-text">确定删除该学生吗？</div>
      <div class="button-container">
        <div class="cancel default" @click="deleteStudentVisible = false">
          取消
        </div>
        <div class="confirm default" @click="onDeleteTargetStudent">确认</div>
      </div>
    </el-dialog>
  </div>
  <create-target-class
    :visible="createVisible"
    :studentList="selectedRow"
    :schoolId="schoolId"
    :teacherId="userInfo.userId"
    @close="handleClose"
  />
</template>
<script setup>
// import Breadcrumb from '@/components/Breadcrumb.vue'
import CreateTargetClass from './components/CreateTargetClass.vue'
import { onMounted, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  getTeachClassList,
  getAdminStudents,
  getTeachStudents,
  getTargetClassStudents,
  postDeleteTargetClass,
  postDeleteTargetStudent,
  getAdminClassList,
  postSetVisibleRange
} from '@/apis/workbench/class-manage/service'
import { useAuthStore } from '@/stores'
import { useRouter } from 'vue-router'

const router = useRouter()
const authStore = useAuthStore()
const userInfo = authStore.userInfo
const multipleTableRef = ref(null)
// const teacherId = '3377357301598883'
const schoolId = ref('')
const curClassId = ref([])
const curClassType = ref('')
const curVisible = ref(1)
const fromPerson = ref('')
const searchKey = ref('')
const selectedRow = ref([])
const createVisible = ref(false)
const deletePopupVisible = ref(false)
const deleteStudentVisible = ref(false)
const activeTab = ref(1)
const total = ref(0)
const curStudent = ref(null)

const pageSize = 100

const CLASS_TYPE = {
  Other: 'class_category|1000',
  AdminClass: 'class_category|1001',
  TeachClass: 'class_category|1002',
  TargetClass: 'target'
}

const VISIBLE_TYPE = {
  OnlySelf: 1, //仅自己
  SameSubject: 2 //同学科可见
}

const treeData = ref([])
const tableData = ref([])
const cascadeVisible = ref(false)
const dropdownVisible = ref(false)

watch(curClassId, newVal => {
  getClassData(newVal[1])
})

watch(activeTab, () => {
  requestGetClassTree()
})

onMounted(async () => {
  // console.log('authStore', authStore.userInfo)
  await requestGetClassTree()
})

const handleShowDropdown = status => {
  dropdownVisible.value = status
}

const expandDropdown = value => {
  cascadeVisible.value = value
}

const handleSelectionChange = val => {
  console.log('选择的', val)
  selectedRow.value = val
}

const onPageChange = page => {
  getClassData(curClassId.value[1], page)
}

const onDeleteTargeClass = async () => {
  const res = await postDeleteTargetClass({ ids: [curClassId.value[1]] })
  if (res.msg === 'success') {
    ElMessage.success('删除成功')
    requestGetClassTree()
    deletePopupVisible.value = false
  } else {
    ElMessage.error(res.msg)
  }
}

/**
 * 单独删除靶向班的学生
 */
const onDeleteTargetStudent = async () => {
  const res = await postDeleteTargetStudent({
    class_id: Number(curClassId.value[1]),
    school_id: Number(schoolId.value),
    student_ids: [Number(curStudent.value.key)]
  })
  if (res.msg === 'success') {
    ElMessage.success('删除成功')
    getClassData(curClassId.value[1])
    deleteStudentVisible.value = false
  } else {
    ElMessage.error(res.msg)
  }
}

const handleShowDeleteStudent = record => {
  curStudent.value = record
  deleteStudentVisible.value = true
}

/**
 * 展示创建弹窗
 */
const onCreate = () => {
  if (!selectedRow.value.length) {
    ElMessage.warning('请选择学生')
    return
  }
  createVisible.value = true
}

const handleClose = message => {
  createVisible.value = false
  if (message === 'refresh') {
    requestGetClassTree()
  }
}

const onSearch = () => {
  getClassData(curClassId.value[1], 1)
}

/**
 * 设置可见范围
 */
const switchVisibleRange = async () => {
  curVisible.value =
    curVisible.value === VISIBLE_TYPE.OnlySelf
      ? VISIBLE_TYPE.SameSubject
      : VISIBLE_TYPE.OnlySelf

  const res = await postSetVisibleRange({
    class_id: curClassId.value[1],
    visible: curVisible.value
  })
  if (res.msg === 'success') {
    ElMessage.success('设置成功')
    const { classItem } = findParentNode(treeData.value, curClassId.value[1])
    classItem.visible = curVisible.value
  } else {
    ElMessage.error(res.msg)
  }
}

/**
 * 获取任教班级树形下拉框
 */
async function requestGetClassTree() {
  const api = activeTab.value === 1 ? getTeachClassList : getAdminClassList
  const res = await api({ teacher_id: Number(userInfo.userId) }) //Number(userInfo.userId)
  const admini_and_teaching_class = res.data.admini_and_teaching_class || []
  const targeted_class = res.data.targeted_class || []
  let _treeData = []

  if (admini_and_teaching_class.length) {
    const index = admini_and_teaching_class.findIndex(
      item => item.school_id === userInfo.school_id
    )
    const realIndex = index >= 0 ? index : 0
    const gradeList = admini_and_teaching_class[realIndex]?.grade_list || []
    schoolId.value = admini_and_teaching_class[realIndex]?.school_id

    gradeList.forEach(gradeItem => {
      const gradeObject = {
        value: gradeItem.grade_id,
        label: gradeItem.grade_name,
        gradeCode: gradeItem.grade_code,
        children: []
      }
      const classList = gradeItem.class_list || []
      classList.forEach(classItem => {
        const classObject = {
          value: classItem.class_id,
          label: classItem.class_name,
          classType: classItem.class_type
        }
        gradeObject.children.push(classObject)
      })
      _treeData.push(gradeObject)
    })
  }

  if (targeted_class.length) {
    const targetClasses = targeted_class.map(item => ({
      value: item.class_id,
      label: item.name,
      classType: CLASS_TYPE.TargetClass,
      teacherName: item.teacher_name,
      visible: item.visible
    }))
    _treeData.push({
      value: 1,
      label: '靶向班',
      children: targetClasses
    })
  }

  if (_treeData.length) {
    treeData.value = _treeData
    curClassId.value = [
      treeData.value[0].value,
      treeData.value[0].children[0].value
    ]
  }
}

/**
 * 处理三种班级学生列表的获取
 */
function getClassData(classId, page) {
  const { classItem } = findParentNode(treeData.value, classId)
  curClassType.value = classItem.classType
  curVisible.value = classItem.visible
  fromPerson.value =
    classItem.classType === CLASS_TYPE.TargetClass ? classItem.teacherName : ''
  switch (classItem.classType) {
    case CLASS_TYPE.TeachClass:
      requestTeachClass(page)
      break
    case CLASS_TYPE.TargetClass:
      requestTargetClass(page)
      break
    default:
      requestAdminClass(page)
  }
}

/**
 * 请求行政班
 */
async function requestAdminClass(page) {
  const { gradeItem } = findParentNode(treeData.value, curClassId.value[1])
  const res = await getAdminStudents({
    page: page || 1,
    page_size: pageSize,
    school_id: Number(schoolId.value),
    grade_id: Number(gradeItem.value),
    class_id: Number(curClassId.value[1]),
    keyword: searchKey.value
  })
  total.value = res.data.total
  const list = res.data.list || []
  tableData.value = list.map((item, index) => {
    const { school_class_info, student_info } = item
    return {
      key: student_info.student_id,
      number: index + 1,
      className: school_class_info.class_name,
      studentName: student_info.username,
      studentNum: student_info.student_id_code,
      gradeId: school_class_info.grade_id,
      gradeName: school_class_info.grade_name
    }
  })
}

/**
 * 请求教学班
 */
async function requestTeachClass(page) {
  const data = {
    page: page || 1,
    page_size: pageSize,
    class_category_code: CLASS_TYPE.TeachClass,
    class_id: Number(curClassId.value[1]),
    school_id: Number(schoolId.value),
    keyword: searchKey.value
  }
  const res = await getTeachStudents(data)
  total.value = res.data.total
  const list = res.data.list || []
  tableData.value = list.map((item, index) => {
    const { school_class_info, student_info } = item
    return {
      key: student_info.student_id,
      number: index + 1,
      className: school_class_info.class_name,
      studentName: student_info.username,
      studentNum: student_info.student_id_code,
      gradeId: school_class_info.grade_id,
      gradeName: school_class_info.grade_name
    }
  })
}

/**
 * 请求靶向班
 */
async function requestTargetClass(page) {
  const res = await getTargetClassStudents({
    page: page || 1,
    page_size: pageSize,
    targeted_class_id: curClassId.value[1],
    keyword: searchKey.value
  })
  total.value = res.data.total
  const list = res.data.list || []
  tableData.value = list.map((item, index) => {
    const { teach_info } = item
    return {
      key: item.student_id,
      number: index + 1,
      className: teach_info.class_name,
      studentName: item.student_name,
      studentNum: item.student_id_code,
      gradeId: teach_info.grade_id,
      gradeName: teach_info.grade_name
    }
  })
}

/**
 * 获取点击树形的选项
 */
function findParentNode(tree, targetValue) {
  for (let node of tree) {
    if (node.children) {
      const childNode = node.children.find(child => child.value === targetValue)
      if (childNode) {
        return { gradeItem: node, classItem: childNode }
      } else {
        const parentNode = findParentNode(node.children, targetValue)
        if (parentNode) {
          return parentNode
        }
      }
    }
  }
  return null
}
</script>
<style lang="less" scoped>
.class-manage {
  height: 95vh;
  display: flex;
  flex-direction: column;

  :deep(.el-dialog) {
    border-radius: 15px;
    width: 400px;
    box-sizing: border-box;
    padding: 40px 40px 25px;
  }

  .tip-text {
    font-size: 22px;
    white-space: nowrap;
    text-align: center;
  }

  .button-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 50px;

    .default {
      width: 120px;
      height: 47px;
      border-radius: 4px;
      font-weight: bold;
      font-size: 20px;
      text-align: center;
      line-height: 47px;
      cursor: pointer;
    }

    .cancel {
      border: 1px solid @color-brand-regular;
      color: @color-brand-regular;
      margin-right: 35px;
    }

    .confirm {
      background: @color-brand-regular;
      color: #fff;
    }
  }
}

.header {
  display: flex;
  align-items: center;
  margin: 17px 0 12px;

  .back-icon {
    width: 13px;
    margin-right: 60px;
    cursor: pointer;
  }

  .tab-container {
    display: flex;
    align-items: flex-end;

    .tab {
      font-weight: 400;
      font-size: 24px;
      color: @color-neutral-title-darker;
      opacity: 0.4;
      cursor: pointer;

      &:first-child {
        margin-right: 40px;
      }
    }

    .active {
      font-weight: bold;
      font-size: 24px;
      color: @color-brand-regular;
      opacity: 1;
    }
  }
}

.main {
  position: relative;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 15px;
  padding: 38px 65px 100px 65px;

  .main-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;

    .left {
      display: flex;
      align-items: center;

      .label {
        font-weight: bold;
        font-size: @size-nav3;
        color: #333;
        margin-right: 9px;
      }

      :deep(.el-cascader) {
        margin-right: 25px;
        width: 198px;
        height: 49px;

        .el-input {
          height: 100%;
        }

        .el-input__wrapper {
          height: 100%;
          box-shadow: 0 0 0 1px @color-brand-unchecked inset;
          border-radius: 5px;
          --el-input-icon-color: @color-brand-unchecked;

          .el-input__inner {
            color: @color-brand-unchecked;
            font-size: @size-nav3;
          }
        }
      }

      :deep(.cascader-checked) {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px @color-brand-checked inset;
          --el-input-icon-color: @color-brand-checked;

          .el-input__inner {
            color: @color-brand-checked;
          }
        }
      }

      :deep(.el-cascader__dropdown.el-popper) {
        border: 1px solid @color-brand-unchecked;
        border-radius: 5px;
        --el-color-primary: @color-brand-checked !important;

        .el-popper__arrow::before {
          border: 1px solid @color-brand-unchecked;
        }

        .el-cascader-node__prefix,
        .el-cascader-node__postfix {
          display: none;
        }

        .el-cascader-panel {
          padding: 10px 0;
          --el-cascader-menu-font-size: @size-base;
        }

        .el-cascader-node__label {
          font-weight: 400;
        }
      }

      .el-input {
        width: 294px;
        height: 49px;

        :deep(.el-input__wrapper) {
          height: 100%;
          box-shadow: 0 0 0 1px @color-brand-unchecked inset;
          border-radius: 5px;

          .el-input__inner::placeholder,
          .el-input__prefix {
            color: @color-brand-unchecked;
          }

          .el-input__inner::placeholder {
            font-size: @size-nav3;
          }

          // .el-input__inner {
          //   margin-left: 23px;
          // }

          // .el-input__prefix-inner {
          //   position: relative;
          //   padding-right: 12px;

          //   &::after {
          //     content: '';
          //     position: absolute;
          //     right: 0;
          //     top: 50%;
          //     transform: translateY(-50%);
          //     height: 14px;
          //     width: 2px;
          //     background: @color-brand-unchecked;
          //     opacity: 0.5;
          //   }
          // }
        }
      }

      // .search-button {
      //   width: 122px;
      //   height: 49px;
      //   background: @color-brand-regular;
      //   border-radius: 4px;
      //   font-weight: 500;
      //   font-size: @size-nav3;
      //   color: #fff;
      //   text-align: center;
      //   line-height: 49px;
      //   margin-left: 10px;
      //   cursor: pointer;
      // }
    }

    .right {
      display: flex;
      align-items: center;
      font-size: @size-nav3;

      .range-container {
        display: flex;
        align-items: center;

        .switch-icon {
          width: 18px;
          margin-right: 5px;
        }
      }

      .split-line {
        position: relative;
        padding-right: 27px;

        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          height: 12px;
          width: 2px;
          background: @color-neutral-title-darker;
          opacity: 0.5;
        }
      }

      .cancel-text {
        font-weight: 500;
        color: @color-brand-regular;
        cursor: pointer;
        margin-right: 25px;
      }

      .default {
        height: 49px;
        padding: 0 24px;
        border-radius: 6px;
        font-weight: bold;
        font-size: @size-nav2;
        line-height: 49px;
        text-align: center;
        cursor: pointer;
      }

      .delete-button {
        border: 1px solid @color-function-danger-dark;
        color: @color-function-danger-dark;
        margin-right: 20px;
      }

      .create-button {
        position: relative;
        background: @color-brand-regular;
        color: #fff;

        .dropdown-container {
          position: absolute;
          z-index: 999;
          top: 140%;
          left: 50%;
          transform: translate(-50%, 0);
          padding-top: 10px;
          border: 1px solid @color-brand-unchecked;
          border-radius: 6px;
          background-color: #fff;

          .triangle {
            width: 25px;
            position: absolute;
            z-index: 999;
            top: -21px;
            left: 50%;
            transform: translate(-50%, 0);
          }

          .student-list {
            box-sizing: border-box;
            min-width: 83px;
            max-height: 320px;
            overflow: hidden scroll;
            padding-top: 20px;
            background-color: #fff;
            border-radius: 6px;

            &::-webkit-scrollbar {
              display: none;
            }

            .name-item {
              text-align: center;
              margin-bottom: 30px;
              color: @color-neutral-title-darker;
              opacity: 0.5;
            }
          }
        }
      }
    }
  }

  :deep(.el-table) {
    flex: 1;

    tr {
      width: 100%;
    }

    th,
    td {
      width: 16.66%;
    }

    .el-table__header {
      table-layout: initial;
    }

    .el-table__header > thead {
      color: rgb(4 11 26 / 0.95);
      height: 58px;
      font-size: @size-nav3;

      tr > th {
        position: relative;
        background-color: @color-neutral-fill-light;

        &:first-child {
          border-radius: 14px 0 0;
        }

        &:last-child {
          border-radius: 0 14px 0 0;
        }

        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          height: 16px;
          width: 2px;
          background: @color-neutral-title-darker;
          opacity: 0.5;
        }
      }

      tr > th:last-child::after {
        content: none;
      }
    }

    .el-table__body {
      width: initial !important;

      tr {
        height: 70px;
        color: rgb(51 51 51 / 0.9);
        font-size: @size-nav3;
      }
    }

    .el-checkbox__inner {
      border: 1px solid @color-brand-unchecked;
    }

    .el-checkbox__input.is-checked,
    .el-checkbox__input.is-indeterminate {
      .el-checkbox__inner {
        background-color: @color-brand-checked;
        border: 1px solid transparent;
      }
    }
  }

  :deep(.el-pagination) {
    position: absolute;
    bottom: 30px;
    right: 25px;

    .btn-prev,
    .btn-next {
      border-radius: 8px;
      border: 1px solid @color-neutral-line-light;
      background-color: #fff;
    }

    .el-pager .number {
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e6e7e8;
    }

    .el-pager .is-active {
      background-color: @color-brand-checked;
    }

    .el-pager .is-active + .number {
      border: 1px solid @color-brand-checked;
    }

    .more {
      background-color: #fff;
    }
  }
}
</style>
